#encoding:utf-8
import time,sys,os,json,datetime
reload(sys)
sys.setdefaultencoding('utf-8')
from  math import ceil
sys.path.append('mymd')
from mymd import sql,ch_tpp
from functools import wraps
from flask import Flask,jsonify,request,render_template,url_for,redirect,session,abort,escape,flash
from werkzeug import secure_filename
from werkzeug.security import generate_password_hash,check_password_hash
#from flask.ext.script import Manager
#app = Flask(__name__)
#manager = Manager(app)

#实例化数据库
mysql=sql.Mysql('127.0.0.1','root','123456','kkk')

#设置上传的路径和扩展名称
UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set(['txt','pdf','png','jpg','jpeg','gif'])

#设置flask
app = Flask(__name__)
#app = Flask(__name__,template_folder="views", static_folder="assets")
app.config.from_envvar('FLASKR_SETTING',silent=True)
app.secret_key = 'DJFDK@426526+--ocPCSWJKJB@MN$klkj#==--'
#app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER          #设置上传目录
#app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  #设置上传限制16M

#设置session过期时间
#session.permanent = True
#app.permanent_session_lifetime = datetime.timedelta(minutes=5)

#验证登录
def check_login(fn):
    @wraps(fn)
    def BtnPrv(*args,**kw):
        if not session.get('username',None):
            return redirect('/login')
        return fn(*args,**kw)
    return BtnPrv

#验证权限
def check_access(fn):
    @wraps(fn)
    def BtnPrv(*args,**kw):
        #if not session.get('userid',None):
        #    return redirect('/login')
        if session.get('access',None) != 1:
            abort(404)
        return fn(*args,**kw)
    return BtnPrv

def check_access2(*nodename):
    def inner(fn):
        @wraps(fn)
        def BtnPrv(*args,**kw):
            sqls='''
        select user.id,node.name,node.mname,role.name
        from user,role,user_role,access,node
        where user.id=%s
        and user.is_active=1 and user.`status`=1
        and (user_role.uid=user.id and user_role.uid = role.id and role.status=1 and user_role.rid=access.rid)
        and (access.nid = node.id and node.`status`=1 and node.name=%s)
        '''
            id = session.get('userid',None)
            res=mysql.read(sqls,[id,nodename[0]])
            if not res:
                abort(403)
            return fn(*args,**kw)
        return BtnPrv
    return inner

#==============================================================
@app.errorhandler(404)
def err_404(e):
    return render_template('404.html'),404


@app.route('/login',methods=['POST','GET'])
def login():
    if request.method=='POST':
        username = request.form.get('username')
        passwd = request.form.get('passwd')
        msg = '账号或密码错误！'
        #passwd = generate_password_hash(passwd)
        #check_password_hash(pwhash, password)
        if username and passwd:
            res = mysql.read('select id,name,email,passwd from user where email=%s and is_active=1 and status=1 limit 1',[username])
            if res:
                id = res[0][0]
                pwhash = res[0][3].decode('utf-8')
                if check_password_hash(pwhash, passwd):
                    session['userid'] = id
                    session['username'] = username
                    return redirect(url_for('index'))
        return render_template('login.html',msg=msg)
    else:
        return render_template('login.html')


@app.route('/')
@check_login
def index():
    pon=session.get('username')
    return render_template('index.html',**locals())


@app.route('/update_passwd',methods=['POST','GET'])
@check_login
def update_passwd():
    username = session.get('username')
    if request.method == 'POST':
        old_passwd = request.form.get('old_passwd')
        new_passwd = request.form.get('new_passwd')
        if old_passwd and new_passwd:
            res = mysql.read('select name,email,passwd from user where email=%s limit 1', [username])
            pwhash = res[0][2].decode('utf-8')
            new_passwd = generate_password_hash(new_passwd)
            if check_password_hash(pwhash, old_passwd):
                mysql.write('update  user set passwd=%s where email=%s limit 1', [new_passwd,username])
                return redirect(url_for('index'))

    return render_template('update_passwd.html',**locals())

@app.route('/upload',methods=['GET','POST'])
@check_login
def upload():
    file_path='static/user/img/'
    if request.method=='POST':
        f=request.files['file']
        try:
            f.save(os.path.join(file_path,secure_filename(f.filename)))
        except:
            pass
        return redirect(url_for('upload'))
    else:
        for root,dirs,files in os.walk(file_path):
            file_list=files
            #print file_list
    return render_template('upload.html',file_list=file_list)


@app.route('/page',methods=['GET','POST'])
#@app.route('/page/<int:count_start>',methods=['GET','POST'])
@check_login
#@check_access2('page')
def page_count(count_start=1,count=10.0):
    #------------------------------------------------------
    s_time=request.args.get('s_time')
    d_time = request.args.get('d_time')
    count_start=request.args.get('count_start',1)
    count = request.args.get('count', 10.0)
    print s_time,d_time,count_start,count
    #-------------------------------------------------------
    wherestr = "WHERE 1=1 "
    if s_time and s_time != 'None': wherestr = ' '.join((wherestr, 'AND  time >= "%s"' % (s_time)))
    if d_time and d_time != 'None': wherestr = ' '.join((wherestr, 'AND  time < "%s"' % (d_time)))
    wherestr2 = wherestr
    sqls_count = '''select count(id) from user {where};'''.format(where=wherestr2)
    total_count = mysql.read(sqls_count)
    #-------------------------------------------------------
    data=[]
    count = float(count)  # 每页行数
    count_start=int(count_start)
    total_page = int(ceil(total_count[0][0] / count))
    total_list = [i + 1 for i in range(total_page)]
    #print total_list
    if count_start >= total_page: count_start = total_page
    if count_start <= 0: count_start = 0
    wherestr = ' '.join((wherestr, 'Order by %s' % ('id asc')))
    wherestr = ' '.join((wherestr, 'Limit %d,%d' % (int((count_start-1) * count), int(count))))
    sqls = '''select id,name,email,passwd,is_active,status,time from user {where};'''.format(where=wherestr)
    print sqls
    #sqls = '''select id,name,email,passwd,is_active,status,time from user where 1=1 and name like ? order by ?  limit ?;'''
    res =mysql.read(sqls,)
    print res
    for i in res:
        data.append(list(i))

    CA={}
    for i in range(total_page):
        if i+1 == count_start:
            CA[i+1] = "active"
            continue
        CA[i+1] = ""
    return render_template('page.html', **locals())




@app.route('/page_ajax',methods=['GET','POST'])
@check_login
@check_access2('page_ajax')
def page_ajax():
    start=request.args.get('start')            #当前页数*行数
    length=request.args.get('length')           #每页的行数
    search=request.args.get('search[value]')    #搜索关键字
    column= request.args.get('order[0][column]') #第几列
    order = request.args.get('order[0][dir]')   #排序
    als= request.args.get('order')
    print als

    d={}
    data=[]
    gg={0:'id',1:'name',2:'email',3:'passwd',4:'is_active',5:'status',6:'time'}
    #print search
    #print column
    #print gg[int(column)]
    #----------------------------------------------------------------------------------------------
    wherestr = "WHERE 1=1 "
    wherestr = wherestr2 = ' '.join((wherestr, "AND (name like %s OR email like %s OR time like %s)"))
    wherestr = ' '.join((wherestr, 'Order by %s %s' % (gg[int(column)],order)))
    wherestr = ' '.join((wherestr, 'Limit %d,%d' % (int(start), int(length))))
    sqls = '''select id,name,email,passwd,is_active,status,time from user {where};'''.format(where=wherestr)
    sqls_count = '''select count(id) from user {where};'''.format(where=wherestr2)
    print sqls_count
    print sqls
    # ----------------------------------------------------------------------------------------------
    res = mysql.read(sqls, ('%' + search + '%', '%' + search + '%', '%' + search + '%'))
    count = mysql.read(sqls_count, ('%' + search + '%', '%' + search + '%', '%' + search + '%'))
    count = count[0][0]
    print count
    for i in res:
        i=list(i)
        i[6]=str(i[6])
        if i[5]==1:i[5]='<font color="green">正常</font>'
        else:i[5]='<font color="red">关闭</font>'
        if i[4] == 1: i[4] = '<font color="green">已激活</font>'
        else:i[4] = '<font color="red">未激活</font>'
        data.append(i)
    print(data)

    d['recordsTotal'] = count
    d['recordsFiltered'] = count
    d['data'] = data
    #print d
    return json.dumps(d)



@app.route('/logout')
@check_login
def logout():
    session.pop('username',None)
    return redirect(url_for('login'))


if __name__ == '__main__':
    app.run(host='0.0.0.0',port=80,debug=True,threaded=1)
    # manager.run()
    '''
    python hello.py shell#在flask应用上下文环境中运行python shell，方便测试和调试web环境
    python hello.py runserver#运行flask开发服务器，app.run()
    python hello.py -h#显示帮助信息
    python hello.py runserver --help

　　usage: hello.py runserver [-h] [-t HOST] [-p PORT] [--threaded]
　　[--processes PROCESSES] [--passthrough-errors] [-d]
　　[-r]

    python hello.py runserver -h 0.0.0.0 -p 80#这样就开启了本机的80端口，别的机器可以远程访问了
    '''